<?php
class Magents extends CI_Model
{
	function Magents()
	{
		parent::__construct();
		$this->load->library( 'calendar' );
		$this->load->library( 'enc' );
		$this->load->model( 'mmaster' );
    $this->load->library('upload');
		$this->load->library('serversidedatatables');

	}
    
    function checkAgentId($agent_id){
        $query=$this->db->query("SELECT * from t_mtr_agent where agent_id='".$agent_id."'");       
        echo json_encode($query->result_array());        
    }
	
    
	function saveAgents()
	{
    if ($this->input->post( 'agent_id' )!="" or $this->input->post( 'agent_id' ) !=null)
        $agentID = $this->input->post( 'agent_id' );
    else
        $agentID = $this->generateAgentID();
    $agentName = $this->input->post( 'agent_name' );
		
		$this->db->trans_start();
		
    if ($this->input->post("image"))
    {
  		$file_name = $this->uploadImage();
    }
    
    if($agentName!=""){
		  $this->mmaster->saveTerritory( 'agent', $agentName );
		}
        $this->saveAgentData( $agentID, $file_name );
        $this->saveProgram( $agentID );
		
		if( $this->input->post( 'is_school' ) == 1 )
			$this->saveAgentSchool( $agentID );
		
		$this->savePICData( $agentID );
		if ($this->db->trans_status() === FALSE)
			$this->db->trans_rollback();
		else{
			$this->db->trans_commit();
            $this->mglobal->saveLog('agent','new',"$agentID");
        }
	}
	
	function uploadImage()
	{
		$config['upload_path'] = './file/agent/';
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '1000';
		$config['max_width']  = '5000';
		$config['max_height']  = '5000';

    //edited by: alfin akhret
		// $this->load->library('upload', $config); 

    $this->upload->initialize($config); //this is better

		// echo $this->upload->do_upload('image');
		// echo $this->upload->display_errors();
		
		// $tmp = $this->upload->data();
		// print_r( $tmp );
    // print_r($tmp['file_name']);die();
		
    $data='';
    
		if ( !$this->upload->do_upload('image'))
		{
			$error = array('error' => $this->upload->display_errors()); 
			// $this->load->view('upload_form', $error);
		}
		else
		{
			$data = array('upload_data' => $this->upload->data());
      return $data['upload_data']['file_name'];
			// $this->load->view('upload_success', $data);
		}
   
	}
	
	function saveAgentData( $agent_id, $file_name = "-" )
	{
		$data = array();
		$parent_id = $this->mmaster->getTerritory( $this->session->userdata( 'username' ) )->row()->territory_id;
		$this->db->select_max( 'territory_id' );
		$data[ 'agent_id' ] = $agent_id;
		$data[ 'territory_id' ] = $this->db->get_where( 't_mtr_territory', array( 'parent_id' => $parent_id ) )->row()->territory_id;
		$data[ 'agent_name' ] = $this->input->post( 'agent_name' );
		$data[ 'agent_address' ] = $this->input->post( 'agent_address' );
		$data[ 'agent_city' ] = $this->input->post( 'agent_city' );
		$data[ 'agent_province_id' ] = $this->input->post( 'agent_province' );
		$data[ 'agent_zip_code' ] = $this->input->post( 'agent_zip_code' );
		$data[ 'agent_phone_no' ] = $this->input->post( 'agent_phone_no' );
		$data[ 'agent_status' ] = $this->input->post( 'agent_type' );
		$data[ 'agent_mdn_evo' ] = $this->input->post( 'mdn_evo' );
		$data[ 'agent_number_of_employee' ] = "0";//$this->input->post( 'employee_num' );
		$data[ 'is_agent_a_school' ] = $this->input->post( 'is_school' );
		$data[ 'agent_location' ] = $this->input->post( 'agent_location' );
		$data[ 'agent_type' ] = $this->input->post( 'agent_type' );
        //$data[ 'agent_status' ] = $this->input->post( 'agent_type' );
        $data[ 'agent_selling_type' ] = $this->input->post( 'agent_selling_type' );
		$data[ 'agent_business_focus' ] = $this->input->post( 'b_focus' );
		$data[ 'agent_website' ] = $this->input->post( 'agent_website' );
		$data[ 'image_path' ] = $file_name;
        if($this->input->post('datastatus')==1)
            $data[ 'istatus' ] = '3';
        else
            $data[ 'istatus' ] ='0';
        
		$data[ 'created_by' ] = $this->session->userdata( 'username' );
		//$data[ 'created_on' ] = date("Y-m-d H:i:s");
		$data[ 'updated_by' ] = $this->session->userdata( 'username' );
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
		
		$this->db->insert( 't_mtr_agent', $data );
        $lastId = $this->db->insert_id();
		$this->mglobal->saveLog('agent-detail-data','new','(header='.$agent_id.' detail='.$lastId.')');
	}
	
	function saveAgentSchool( $agent_id )
	{
		$data = array();
		$data[ 'agent_id' ] = $agent_id;
		$data[ 'school_number_of_faculty' ] = $this->input->post( 'faculty_num' );
		$data[ 'school_number_of_student' ] = $this->input->post( 'student_num' );
		$data[ 'school_number_of_teacher' ] = $this->input->post( 'teacher_num' );
		$data[ 'school_number_of_majority' ] = $this->input->post( 'majority_num' );
		$data[ 'created_by' ] = $this->session->userdata( 'username' );
		//$data[ 'created_on' ] = date("Y-m-d H:i:s");
		$data[ 'updated_by' ] = $this->session->userdata( 'username' );
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
		
		$this->db->insert( 't_mtr_agent_school', $data );
	}
	
	function savePICData( $agent_id )
	{
		$data = array();
		$data[ 'agent_id' ] = $agent_id;
		$data[ 'pic_name' ] = $this->input->post( 'pic_name' );
		$data[ 'pic_address' ] = $this->input->post( 'pic_address' );
		$data[ 'pic_city' ] = $this->input->post( 'pic_city' );
		$data[ 'pic_province_id' ] = $this->input->post( 'pic_province' );
		$data[ 'pic_zip_code' ] = $this->input->post( 'pic_zip_code' );
		$data[ 'pic_phone_no' ] = $this->input->post( 'pic_phone_no' );
		$data[ 'pic_identity_type' ] = $this->input->post( 'pic_identity_type' );
		$data[ 'pic_identity_no' ] = $this->input->post( 'pic_identity_no' );
		$data[ 'pic_birth_place' ] = $this->input->post( 'pic_birth_place' );
		if($this->input->post('pic_birth_date'))
            $data[ 'pic_birth_date' ] = $this->input->post( 'pic_birth_date' );		
        $data[ 'pic_job_position' ] = $this->input->post( 'pic_job_position' );
		$data[ 'pic_smartfren_no' ] = $this->input->post( 'smartfren_no' );
		$data[ 'pic_mobile_no' ] = $this->input->post( 'mobile_no' );
		$data[ 'pic_email' ] = $this->input->post( 'pic_email' );
		if($this->input->post('datastatus')==1)
            $data[ 'istatus' ] = '3';
        else
            $data[ 'istatus' ] ='0';
		$data[ 'created_by' ] = $this->session->userdata( 'username' );
		//$data[ 'created_on' ] = date("Y-m-d H:i:s");
		$data[ 'updated_by' ] = $this->session->userdata( 'username' );
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
		
		$this->db->insert( 't_mtr_agent_pic', $data );
        $lastId = $this->db->insert_id();
		$this->mglobal->saveLog('agent-pic-data','new','(header='.$agent_id.' detail='.$lastId.')');
	}
	
	//by: alfin akhret
	function update_message($user_id, $msg_from, $msg_to, $msg_subject)
	{	

		//cari user name dari si pengirim pesan (yg aproove outlet)
		$this->db->select('user_name');
		$query = $this->db->get_where('t_mtr_user', array('user_id' => $user_id));
		$username = '';
		foreach ($query->result() as $r) 
		{
			$username = $r->user_name;	
		}
		
		$msg_body = "Agent " .$msg_to ." telah disetujui oleh ". $username; //letakan nama pengirim pada bagian body text

		//cari user_id recipient
		$this->db->select('territory_id');
		$query = $this->db->get_where('t_mtr_agent', array('agent_id' => $msg_to));
		foreach ($query->result() as $r) 
		{
			$territory_id = $r->territory_id;
			$this->db->select('user_id');
			$query2 = $this->db->get_where('t_mtr_territory', array('territory_id' => $territory_id));
			foreach ($query2->result() as $r2) 
			{
				$msg_to = $r2->user_id;	
			}	
		}

		$data = array(
				'msg_from' => $msg_from,
				'msg_to' => $msg_to,
				'msg_subject' => $msg_subject,
				'msg_body' => $msg_body,
				'created_by' => $user_id 
			);

		$this->db->insert('t_msg', $data);
	}

	function updateAgents( $proses, $agent_id, $territory_id, $is_school_before )
	{
    $this->saveProgram( $agent_id );
		$istatus = $this->db->get_where( 't_mtr_agent', array( 'agent_id' => $agent_id ) )->row()->istatus;
		
		$this->db->trans_start();
		
		if( $proses == 'update' )
		{
			$maintain_name = $this->input->post( 'maintain_name' );

      // edited by: alfin akhret
      //ini aneh lhooo.... 
      // datanya udah null, tapi di null kan lagi, kalo gak prosesnya jadi error lhoooo...
      if($maintain_name == null)
      {
        $maintain_name = null;
      }

      // echo $maintain_name;die();

			$agent_name = $this->input->post( 'agent_name' );

			$this->db->get_where('t_mtr_agent_pic',array( 'agent_id = ' => $agent_id ));

      //agent pic id  = 4 
                
			$data = array(
						'territory_name' => $agent_name,
						'user_id' => $maintain_name
					);
			
             if( $istatus == 0 or $istatus==3 )
             {				// $this->db->update( 't_mtr_territory', $data, array( 'territory_id =' => $territory_id ) );
                    $this->db->where('territory_id', $territory_id);
                    $this->db->update('t_mtr_territory', $data);
            }
		          else //if( $istatus == 1 )
            {


                      $query = $this->db->get_where( 't_mtr_territory', array( 'territory_id' => $territory_id ));
                      $query = $query->row();
                      $t_id = $query->territory_id;
                      $p_id = $query->parent_id;
                      $tt_id = $query->territory_type_id;

                      $query = $this->db->get_where('t_mtr_territory_unapproved', array('territory_id' => $t_id));

                      //updated by : alfin akhret <alfin.akhret@gmail.com>
                      //21 sept 2012
                      
                      if($query->num_rows() >= 1)
                      {

                        $data[ 'updated_by' ] = $this->session->userdata( 'username' );
                        $data[ 'updated_on' ] = date("Y-m-d H:i:s");
                        $this->db->where('territory_id', $territory_id);
                        $this->db->update( 't_mtr_territory_unapproved', $data);
                      }
                      else
                      {
                        $data['territory_type_id'] = $tt_id;
                        $data['parent_id'] = $p_id;
                        $data['territory_id'] = $t_id;
                        $data[ 'updated_by' ] = $this->session->userdata( 'username' );
                        $data[ 'updated_on' ] = date("Y-m-d H:i:s");
                        $this->db->insert( 't_mtr_territory_unapproved', $data );
                      }


              				// $this->db->insert( 't_mtr_territory_unapproved', $query );
              				// $data[ 'updated_by' ] = $this->session->userdata( 'username' );
              				// $data[ 'updated_on' ] = date("Y-m-d H:i:s");
                  //     $this->db->where('territory_id', $territory_id);
              				// $this->db->update( 't_mtr_territory_unapproved', $data);
            }
             
			
			$data = array();
			$data[ 'agent_name' ] = $agent_name;
			$data[ 'agent_address' ] = $this->input->post( 'agent_address' );
			$data[ 'agent_city' ] = $this->input->post( 'agent_city' );
			$data[ 'agent_province_id' ] = $this->input->post( 'agent_province' );
			$data[ 'agent_zip_code' ] = $this->input->post( 'agent_zip_code' );
			$data[ 'agent_phone_no' ] = $this->input->post( 'agent_phone_no' );
			//$data[ 'agent_status' ] = $this->input->post( 'agent_status' );
			$data[ 'agent_mdn_evo' ] = $this->input->post( 'mdn_evo' );
			$data['agent_selling_type'] = $this->input->post('agent_selling_type');
      //edited by: alfin akhret
            
			$file_name = $this->uploadImage();

			if($file_name) $data[ 'image_path' ] = $file_name;
			
			$data[ 'agent_number_of_employee' ] = "0";//$this->input->post( 'employee_num' );
			$data[ 'is_agent_a_school' ] = $this->input->post( 'is_school' );
			$data[ 'agent_location' ] = $this->input->post( 'agent_location' );
			$data[ 'agent_type' ] = $this->input->post( 'agent_type' );
			$data[ 'agent_business_focus' ] = $this->input->post( 'b_focus' );
			$data[ 'agent_website' ] = $this->input->post( 'agent_website' );
			$data[ 'agent_status' ] = $this->input->post( 'agent_type' );		
            
      if( $istatus == 0 or $istatus==3 )
      {
        if($this->input->post('datastatus')==1)
        {
          $data['istatus']=3;
        } 
        else 
        {
          $data['istatus']=0;    
        }

          // print_r($data);die();
          // $this->db->update( 't_mtr_agent', $data, array( 'agent_id = ' => $agent_id ) );
          $this->db->where('agent_id', $agent_id);
          $this->db->update('t_mtr_agent', $data);
			} 
      else 
      {
                    
                    $query = $this->db->get_where( 't_mtr_agent', array( 'agent_id = ' => $agent_id ) )->result_array();
    				$this->db->delete('t_mtr_agent_unapproved', array( 'agent_id' => $agent_id ));
    				$data[ 'updated_by' ] = $this->session->userdata( 'username' );
    				//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
                    $data['territory_id']=$query[0]['territory_id'];
                    $data['agent_id']=$agent_id;
    				$this->db->insert( 't_mtr_agent_unapproved', $data);
    				 if($this->input->post('datastatus')==1)
				        $data['istatus']=4;
				    else
                        $data['istatus']=2;
                        
                    $this->db->update( 't_mtr_agent', array( 'istatus' => $data['istatus'] ), array( 'agent_id = ' => $agent_id ) );
                   
            }
			
			/**
             * if( $data[ 'is_agent_a_school' ] == true )
             * 			{
             * 				$data = array();
             * 				$data[ 'school_number_of_faculty' ] = $this->input->post( 'faculty_num' );
             * 				$data[ 'school_number_of_student' ] = $this->input->post( 'student_num' );
             * 				$data[ 'school_number_of_teacher' ] = $this->input->post( 'teacher_num' );
             * 				$data[ 'school_number_of_majority' ] = $this->input->post( 'majority_num' );
             * 			}
             * 			
             * 			if( $is_school_before == true && $this->input->post( 'is_school' ) == true )
             * 			{					
             * 				if( $istatus == 0 )
             * 					$this->db->update( 't_mtr_agent_school', $data, array( 'agent_id = ' => $agent_id ) );
             * 				else if( $istatus == 1 )
             * 				{
             * 					$query = $this->db->get_where( 't_mtr_agent_school', array( 'agent_id = ' => $agent_id ) )->row();
             * 					$this->db->insert( 't_mtr_agent_school_unapproved', $query );
             * 					$data[ 'updated_by' ] = $this->session->userdata( 'username' );
             * 					//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
             * 					$this->db->update( 't_mtr_agent_school_unapproved', $data, array( 'agent_id = ' => $agent_id ) );
             * 				}
             * 			}
 */
			//else if( $is_school_before == false && $data[ 'is_agent_a_school' ] == true )
				//$this->saveAgentSchool( $agent_id );
			//else if( $is_school_before == true && $data[ 'is_agent_a_school' ] == false )
				//$this->deleteAgentSchool( $agent_id );
				
			$data = array();
			$data[ 'pic_name' ] = $this->input->post( 'pic_name' );
			$data[ 'pic_address' ] = $this->input->post( 'pic_address' );
			$data[ 'pic_city' ] = $this->input->post( 'pic_city' );
			$data[ 'pic_province_id' ] = $this->input->post( 'pic_province' );
			$data[ 'pic_zip_code' ] = $this->input->post( 'pic_zip_code' );
			$data[ 'pic_phone_no' ] = $this->input->post( 'pic_phone_no' );
			$data[ 'pic_identity_type' ] = $this->input->post( 'pic_identity_type' );
			$data[ 'pic_identity_no' ] = $this->input->post( 'pic_identity_no' );
			$data[ 'pic_birth_place' ] = $this->input->post( 'pic_birth_place' );
            if($this->input->post( 'pic_birth_date' ) !='' or $this->input->post( 'pic_birth_date' ) !=null)
                $data[ 'pic_birth_date' ] = $this->input->post( 'pic_birth_date' );
			$data[ 'pic_job_position' ] = $this->input->post( 'pic_job_position' );
			$data[ 'pic_smartfren_no' ] = $this->input->post( 'smartfren_no' );
			$data[ 'pic_mobile_no' ] = $this->input->post( 'mobile_no' );
			$data[ 'pic_email' ] = $this->input->post( 'pic_email' );
			$datss=$this->db->query("SELECT count(*) as jumlah from t_mtr_agent_pic where agent_id='".$agent_id."'");
               // return json_encode($datss->row()->jumlah);
                //return;
			if( $istatus == 0 or $istatus==3 ){
                if($this->input->post('datastatus')==1){
                    $data['istatus']=3;
                } else {
                    $data['istatus']=0;    
                }
                
                if ($datss->row()->jumlah){
    				$this->db->update( 't_mtr_agent_pic', $data, array( 'agent_id = ' => $agent_id ) );
                } else {
                    $data['agent_id']=$agent_id;
                   	$this->db->insert( 't_mtr_agent_pic', $data );
                }
			}else //if( $istatus == 1 )
			{
			//	$query = $this->db->get_where( 't_mtr_agent_pic', array( 'agent_id = ' => $agent_id ) )->row();
				$data[ 'updated_by' ] = $this->session->userdata( 'username' );
				//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
					
			//	if( $query != null )
		//		{
				    $this->db->delete('t_mtr_agent_pic_unapproved', array( 'agent_id' => $agent_id ));
                    $data[ 'agent_id' ] = $agent_id;
					$this->db->insert( 't_mtr_agent_pic_unapproved', $data );
				//	$this->db->update( 't_mtr_agent_pic_unapproved', $data, array( 'agent_id = ' => $agent_id ) );
		//		}
		//		else
		//		{
					
		//			$this->db->insert( 't_mtr_agent_pic_unapproved', $data );
		//		}
			}
		}
		else
		{
			if( $istatus == 4 )
			{
				$tr_query = $this->db->get_where( 't_mtr_territory_unapproved', array( 'territory_id' => $territory_id ) )->result_array();
				$agent_query = $this->db->get_where( 't_mtr_agent_unapproved', array( 'agent_id' => $agent_id ) )->row();
			//	$school_query = $this->db->get_where( 't_mtr_agent_school_unapproved', array( 'agent_id' => $agent_id ) )->row();
				$pic_query = $this->db->get_where( 't_mtr_agent_pic_unapproved', array( 'agent_id' => $agent_id ) )->row();
				$bank_query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'territory_id' => $territory_id ) )->row();
				
				if( $tr_query != null )
				{
				    unset($tr_query[0]['id']);
					$this->db->update( 't_mtr_territory', $tr_query[0], array( 'territory_id' => $territory_id ) );
					$this->db->delete( 't_mtr_territory_unapproved', array( 'territory_id' => $territory_id ) );
				}
				if( $agent_query != null )
				{
					$this->db->update( 't_mtr_agent', $agent_query, array( 'agent_id' => $agent_id ) );
					$this->db->delete( 't_mtr_agent_unapproved', array( 'agent_id' => $agent_id ) ) ;
				}
				
			//	if( $school_query != null )
				//{
				//	$this->db->update( 't_mtr_agent_school', $school_query, array( 'agent_id' => $agent_id ) );
					//$this->db->delete( 't_mtr_agent_school_unapproved', array( 'agent_id' => $agent_id ) );
				//}
				
				if( $pic_query != null )
				{
					$query = $this->db->get( 't_mtr_agent_pic', array( 'agent_id' => $agent_id ) )->row();
					
					if( $query != null )
					{
						$this->db->update( 't_mtr_agent_pic', $pic_query, array( 'agent_id' => $agent_id ) );
					}
					else
					{
						$this->db->insert( 't_mtr_agent_pic', $pic_query );
					}	
					$this->db->delete( 't_mtr_agent_pic_unapproved', array( 'agent_id' => $agent_id ) );
				}
				
				if( $bank_query != null )
				{
					$bank_id = $bank_query->bank_account_id;
					
					if( $bank_query->istatus == 0 )
					{
						$query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'bank_account_id' => $bank_id ) )->row();
						$this->db->insert( 't_mtr_bank_account', $query );
						$this->db->update( 't_mtr_bank_account', array( 'istatus' => 1 ), array( 'bank_account_id' => $bank_id ) );
					}
					else if( $bank_query->istatus == 2 )
					{
						$this->db->update( 't_mtr_bank_account_unapproved', array( 'istatus' => 1 ), array( 'bank_account_id' => $bank_id ) );
						$query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'bank_account_id' => $bank_id ) )->row();
						$this->db->update( 't_mtr_bank_account', $query, array( 'bank_account_id' => $bank_id ) );
					}
					else
					{
						$query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'bank_account_id' => $bank_id ) )->row();
						$this->db->insert( 't_mtr_bank_account', $query );
					}
					
					$this->db->delete( 't_mtr_bank_account_unapproved', array( 'territory_id' => $territory_id ) );
				}
			}
			
			$data[ 'istatus' ] = '1';
			$data[ 'updated_by' ] = $this->session->userdata( 'username' );
			//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
		
			$this->db->update( 't_mtr_agent', $data, array( 'agent_id = ' => $agent_id ) );
		}
		
		if ($this->db->trans_status() === FALSE)
			{$this->db->trans_rollback();
            return "Data Gagal Diubah";}
           
		else{
			$this->db->trans_commit();
		      $this->mglobal->saveLog('agent-change-data',$proses,$agent_id);
            return "Data Berhasil Diubah";
        }
        //return $istatus;
	}
	
	function deleteAgents( $table_type, $agent_id )
	{
		if( $table_type == 'temp' )
		{
			$territory_id = $this->db->get_where( 't_mtr_agent', array( 'agent_id' => $agent_id ) )->row()->territory_id;
			$this->db->delete( 't_mtr_territory_unapproved', array( 'territory_id' => $territory_id ) );
			$this->db->delete( 't_mtr_agent_unapproved', array( 'agent_id' => $agent_id ) ) ;
			$this->db->delete( 't_mtr_agent_school_unapproved', array( 'agent_id' => $agent_id ) );
			$this->db->delete( 't_mtr_agent_pic_unapproved', array( 'agent_id' => $agent_id ) );
			
			$query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'territory_id' => $territory_id ) )->row();
			if( $query != null )
			{
				$this->db->insert( 't_mtr_bank_account', $query );
				$bank_id = $query->bank_account_id;
				$this->db->update( 't_mtr_bank_account', array( 'istatus' => 1 ), array( 'bank_account_id' => $bank_id ) );
				$this->db->delete( 't_mtr_bank_account_unapproved', array( 'territory_id' => $territory_id ) );
			}
			
			$this->db->update( 't_mtr_agent', array( 'istatus' => 1 ), array( 'agent_id = ' => $agent_id ) );
		}
		else
			$this->db->update( 't_mtr_agent', array( 'istatus' => -5 ), array( 'agent_id = ' => $agent_id ) );
            
         $this->mglobal->saveLog('agent-detele-data','delete',$agent_id);
	}
	
	
	// function getAgents($kindOfRecord="", $id = "")
	// {    
	// 	if( $id == "" )
	// 	{
	// 	  $dbconn  = $this->load->database("default", TRUE);
	// 		$userlogin = $this->session->userdata('username');
            
 //            //ambil data usergroup
 //            $user_group=$this->db->query("SELECT user_group_id from t_mtr_user where user_id='".$this->session->userdata('username')."'")->row()->user_group_id;
 //            //ambil data cluster
	// 		$cluster=$this->db->query("SELECT f_get_cluster('".$this->session->userdata('username')."') as cluster")->row()->cluster;

 //            if( $kindOfRecord == 'new' ){
	// 		    if ($user_group=='4')
 //                    $flag=3;
 //                else
 //                    $flag=0;
 //                //original query                
 //                $query = $this->db->query("SELECT agt.* FRoM t_mtr_agent agt inner join t_mtr_territory ter on agt.territory_id=ter.territory_id where ter.parent_id=$cluster and agt.istatus=$flag limit 100");
	// 		}else if( $kindOfRecord == 'registered' ){
 //                $flag=1;
	// 			$query = $this->db->query( "SELECT agt.* FRoM t_mtr_agent agt inner join t_mtr_territory ter on agt.territory_id=ter.territory_id where ter.parent_id=$cluster and agt.istatus=$flag limit 100");
	// 			//$query = $this->db->get_where( 't_mtr_agent', array(  'istatus'=>1 ) )->limit(1);
	// 		}else{
 //                if ($user_group=='4')
 //                    $flag=4;
 //                else
 //                    $flag=2;
	// 			$query = $this->db->query( "SELECT agt.* FRoM t_mtr_agent agt inner join t_mtr_territory ter on agt.territory_id=ter.territory_id where ter.parent_id=$cluster and agt.istatus=$flag limit 100");
	// 		}//	$query = $this->db->get_where( 't_mtr_agent_unapproved', array('istatus'=>0 ) )->limit(1);
			
			
	// 		//$sql = "SELECT sp_grid_agent('$userlogin','$status')";
				
	// 		//$dbconn->query($sql);
			
	// 		//$query = $this->db->get_where( 't_grid_agent', array( 'user_id' => $userlogin ) );
				
	// 		if( $query->num_rows() > 0 ) 
	// 		{
	// 			$i = 0;
	// 			foreach( $query->result() as $row )
	// 			{
	// 				$result[ $i ]->agent_id = $row->agent_id;
	// 				$result[ $i ]->agent_name = $row->agent_name;
	// 				$result[ $i ]->agent_address = $row->agent_address;
	// 				$result[ $i ]->image_path = $row->image_path;
	// 				$result[ $i ]->long = $row->lon;
	// 				$result[ $i ]->lat = $row->lat;
	// 				$i++;
	// 			}
				
	// 			return $result;
	// 		} 
	// 		else 
	// 		{
	// 			return array();
	// 		}
	// 	}
	// 	else
	// 	{
	// 		return $this->db->get_where( 't_mtr_agent', array( 'agent_id' => $id ) )->row();
	// 	}
	// }

	function getAgents($kindOfRecord="", $id = "")
	{
		$user_group=$this->db->query("SELECT user_group_id from t_mtr_user where user_id='".$this->session->userdata('username')."'")->row()->user_group_id;
        //ambil data cluster
		$cluster=$this->db->query("SELECT f_get_cluster('".$this->session->userdata('username')."') as cluster")->row()->cluster;
		
		if ($id == "") 
		{
            if( $kindOfRecord == 'new' ){
                if ($user_group=='4')
                    $flag=3;  //CC tinggal Approve
                else
                    $flag=0;  //Masih Di CA, belum lengkap              
            }else if( $kindOfRecord == 'registered' ){
                $flag=1;      //Sudah Di Approve
                //$query = $this->db->get_where( 't_mtr_agent', array(  'istatus'=>1 ) )->limit(1);
            }else{
                if ($user_group=='4')
                    $flag=4;  //Edit, tampil di CC, sudah lengkap
                else
                    $flag=2;  //Edit, tampil di CA, belum lengkap
            }
		  

			$sIndexColumn = "agent_id"; //index column untuk kecepatan akses data
			$defaultOrder = "0"; //default order berdasarkan field yg ada pada $aColumns
			$userlogin = $this->session->userdata('username'); //user credentials
			// $aColumns = array("agent_id", "agent_name", "agent_address", "image_path", "lon", "lat"); //field2 yg akan ditampilkan pada dataTables
			$aColumns = array("agent_id", "agent_name", "agent_address", "user_name", "image_path"); //field2 yg akan ditampilkan pada dataTables

      if($flag != '4')
      {
			   //SQL query 
			   $inputQuery = "
               	SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
               	FROM t_mtr_agent inner join t_mtr_territory on t_mtr_agent.territory_id = t_mtr_territory.territory_id left join t_mtr_user on t_mtr_territory.user_id = t_mtr_user.user_id
               	where t_mtr_territory.parent_id = '".$cluster."' and t_mtr_agent.istatus = '".$flag."'";
      }
      else
      {
          $inputQuery = "
                SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
                FROM v_ssp_agent_edited where parent_id = '".$cluster."' and istatus1 = '".$flag."'";
                
      }
           //execute datatables serversideprocess
			return $this->serversidedatatables->executeServerSideProcess($defaultOrder, $flag, $userlogin, $inputQuery, $aColumns, $sIndexColumn);
		}
        else
		{
			return $this->db->get_where( 't_mtr_agent', array( 'agent_id' => $id ) )->row();
		}
	}
	
    function getUnapprovedAgents( $id = "")
	{    
		if( $id == "" )
		{
		  $dbconn  = $this->load->database("default", TRUE);
			$userlogin = $this->session->userdata('username');
            //$user_group=$this->db->query("SELECT user_group_id from t_mtr_user where user_id='".$this->session->userdata('username')."'")->row()->user_group_id;     
				$query = $this->db->query( "SELECT agt.* FRoM t_mtr_agent_unapproved agt where agent_id='".$id."'");
			
			if( $query->num_rows() > 0 ) 
			{
				$i = 0;
				foreach( $query->result() as $row )
				{
					$result[ $i ]->agent_id = $row->agent_id;
					$result[ $i ]->agent_name = $row->agent_name;
					$result[ $i ]->agent_address = $row->agent_address;
					$result[ $i ]->image_path = $row->image_path;
					$result[ $i ]->long = $row->lon;
					$result[ $i ]->lat = $row->lat;
					$i++;
				}
				
				return $result;
			} 
			else 
			{
				return array();
			}
		}
		else
		{
			return $this->db->get_where( 't_mtr_agent_unapproved', array( 'agent_id' => $id ) )->row();
		}
	}
    
	function getPIC( $id="" )
	{
		return $this->db->get_where( 't_mtr_agent_pic', array( "agent_id" => $id ) )->row();
	}
    
    function getUnapprovedPIC( $id="" )
	{
		return $this->db->get_where( 't_mtr_agent_pic_unapproved', array( "agent_id" => $id ) )->row();
	}
	
	function getAgentSchool( $id="" )
	{
		return $this->db->get_where( 't_mtr_agent_school', array( "agent_id" => $id ) )->row();
	}
	
	function generateAgentID()
	{

    // echo $this->input->post('agent_selling_type');die();

		//$this->db->select_max( 'agent_id' );
		$record = $this->db->query( "SELECT count(*) as agent_id from t_mtr_territory where parent_id=f_get_cluster('".$this->session->userdata('username')."')" );
       // $territory=$this->db->query("SELECT f_get_cluster('".$this->session->userdata('username')."')")->row();
        $result2 = $this->db->query("SELECT territory_code_v2 from t_mtr_territory_code where territory_id=f_get_cluster('".$this->session->userdata('username')."')")->row()->territory_code_v2;
		//$territory=$this->db->Query("SELECT territory_id from t_mtr_territory where territory_id=(SELECT parent_id from t_mtr_territory t2 where t2.territory_id=f_get_cluster('".$territory."' )");
        $result=$this->db->query("SELECT territory_code from t_mtr_territory_code where territory_id=(SELECT territory_id from t_mtr_territory where territory_id=(SELECT parent_id from t_mtr_territory where territory_id=f_get_cluster('".$this->session->userdata('username')."')))")->row()->territory_code;
       // $result_cluster_code= explode(' ',$result2);
        
       // if($result_cluster_code[1]<10){
       //     $clu_code='0'.$result_cluster_code[1];
       // }
      //  else {
      //      $clu_code=$result_cluster_code[1];
       // }
      if($this->input->post('agent_selling_type') == '1')
      {
        $result.=$result2.'A';
      }
      else if($this->input->post('agent_selling_type') == '2')
      {
        $result.=$result2.'M';
      }
		//if( $record->num_rows() == 0 )
		//	$result = $result.'00001';
	//	else
		{
			$agentId = $record->row()->agent_id;
		//	$agentId = substr( $agentId, 5);
			
			if( $agentId < 10 )
				$loop = 4;
			else if( $agentId < 100 )
				$loop = 3;
			else if( $agentId < 1000 )
				$loop = 2;
			else if($agentId<10000)
				$loop = 1;
			else
                $loop =0;	
			for( $i = 0 ; $i < $loop ; $i++ )
			{
				$result = $result.'0';
			}
			
			$result = $result.( $agentId + 1 );
		}
		
		return $result;
	}


  public function saveProgram($agent_id) {

    $user_id = $this->session->userdata("username");
    $this->db->delete('t_mtr_channel_program', array('channel_id' => $agent_id)); 
    $prorgam_id = $this->input->post("program_id");

    foreach ($prorgam_id as $program) {
      $data = array(
        "channel_id" => $agent_id, 
        "program_id" => $program, 
        "created_by" => $user_id, 
        "updated_by" => $user_id
        );
      // print_r($data); $this->db->trans_rollback(); die();
      $this->db->insert("t_mtr_channel_program", $data );
      $lastId = $this->db->insert_id();
      $this->mglobal->saveLog('outlet-program', 'update' ,'(header='.$agent_id.' detail='.$lastId.')');
    }
  }
 
}?>